/***
 * @Author: 玄绮 shijiahansi@qq.com
 * @Date: 2024-06-06 17:21:07
 * @LastEditors: 玄绮 shijiahansi@qq.com
 * @LastEditTime: 2024-06-06 17:21:11
 * @FilePath: \server\src\http_server\main.cpp
 * @Description:
 * @
 * @Copyright (c) 2024 by 玄绮, All Rights Reserved.
 */

#include "HttpSession.hpp"

#include <HttpServer.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/erase.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/asio.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/beast.hpp>
#include <boost/beast/core/error.hpp>
#include <boost/date_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <filesystem>
#include <iostream>
#include <string>

using namespace std;
using namespace boost::date_time;
using namespace boost::gregorian;
namespace fs = filesystem;

#include <FormItem.h>
#include <string/stringsplit.h>

using namespace rdhttp;

void initServer(HttpServer& server) {
    server.post("/uploadfile") = [&](HttpSession::HttpRequest& request, HttpResponse& response) {
        std::cout << "initServer:" << std::endl;

        auto content_type = ContentType(request[HttpFiled::content_type]);

        if (content_type == ContentType::multipart_form_data) {
            auto& forms = request.forms();

            for (auto& i : forms) {
                auto filename = i.content_dispotion().filename();
                fs::path path(server.doc_root);

                boost::gregorian::date dateToday = boost::gregorian::day_clock::local_day();
                auto today                       = boost::gregorian::to_iso_extended_string(dateToday);

                path /= today;
                path /= filename;
                if (i.save_as(path))
                    response.body() = path.string();
            }
        }
        response.result(HttpStatus::ok);
    };
}

int main(int argc, char const* argv[]) {
    string doc_root   = "./http";
    std::int32_t port = 4091;
    boost::asio::io_context ctx;
    HttpServer server{ctx, port, doc_root};
    initServer(server);
    ctx.run();
    return 0;
}
